package br.urca.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class CryptDoc {
	
	public static final String SECRET_KEY_ANDROID = "5MtKMGV0zR+mg,JO tbdS>YiEov xddB~)E5MO;I2c)^~Ey)a3oV#1X*=dMy{TBU";
	
	static byte[] raw = new byte[]{'#', '@', ',', '.', 'U', 'r', 'C', '@', 'W', 'e', 'B', 's', '&', 'r', 'v', 'R'};	
	
	public static final String KEY = "#@,.UrC@WeBs&rvR";

	static IvParameterSpec iv = new IvParameterSpec(raw);
	
	public static void main(String[] args) {
		String encrypt = encrypt("20112103049");
	    System.out.println("decrypted value:" + (decrypt(KEY, encrypt)));
	}
	
	public static String encrypt(String value) {
	    try {

	        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
	        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
	        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
	        byte[] encrypted = cipher.doFinal(value.getBytes());
	        System.out.println("encrypted string:" + Base64.encodeToString(encrypted, Base64.URL_SAFE | Base64.NO_WRAP));
	        return Base64.encodeToString(encrypted, Base64.URL_SAFE);
	    } catch (Exception ex) {
	        ex.printStackTrace();
	    }
	    return null;
	}
	
	public static String decrypt(String key, String encrypted) {
	    try {
	        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
	        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
	        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
	        byte[] original = cipher.doFinal(Base64.decode(encrypted, Base64.URL_SAFE | Base64.NO_WRAP));

	        return new String(original);
	    } catch (Exception ex) {
	        ex.printStackTrace();
	    }
	    return null;
	}
	
	public static String decrypt(String encrypted) {
	    try {
	        SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes(), "AES");
	        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
	        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
	        byte[] original = cipher.doFinal(Base64.decode(encrypted, Base64.URL_SAFE | Base64.NO_WRAP));

	        return new String(original);
	    } catch (Exception ex) {
	        ex.printStackTrace();
	    }
	    return null;
	}
	
	public static String getB64Auth(String login, String pass) {
		String source = Criptografia.criptografarMD5(login) + ":" + Criptografia.criptografarMD5(pass);
		String ret = "Basic "
				+ Base64.encodeToString(source.getBytes(), Base64.URL_SAFE
						| Base64.NO_WRAP);
		return ret;
	}

}
